﻿// -----------------------------------------------------------------------
// <copyright file="ImageHelper.cs" company="FCIS">
// You are welcome to do whatever you want with the code in this file
// </copyright>
// -----------------------------------------------------------------------

namespace ImagePackage.CommandLine
{
    using System.Text;
    using Model;

    /// <summary>
    /// Extension Class to add ToAscii functionality
    /// </summary>
    public static class ImageHelper
    {
        /// <summary>
        /// Extends model image to return the ASCII representation.
        /// </summary>
        /// <param name="image">The image.</param>
        /// <returns>string ascii representation</returns>
        public static string ToAscii(this Image image)
        {
            string[] asciiChars = { "#", "#", "@", "%", "=", "+", "*", ":", "-", ".", " " };

            bool toggle = false;
            StringBuilder sb = new StringBuilder();

            for (int h = 0; h < image.Height; h++)
            {
                for (int w = 0; w < image.Width; w++)
                {
                    Pixel pixel = image[w, h];

                    int gray = (pixel.Blue + pixel.Green + pixel.Red) / 3;
                    
                    // Use the toggle flag to minimize height-wise stretch
                    if (!toggle)
                    {
                        int index = (gray * 10) / 255;
                        sb.Append(asciiChars[index]);
                    }
                }

                if (!toggle)
                {
                    sb.Append("\n");
                    toggle = true;
                }
                else
                {
                    toggle = false;
                }
            }

            return sb.ToString();
        }
    }
}
